import BasePlugin from './BasePlugin';
import * as fabricModule from 'fabric';
const fabric = fabricModule.fabric || fabricModule;

/**
 * 图片插件 - 处理图片对象的创建和操作
 */
export default class ImagePlugin extends BasePlugin {
    constructor() {
        super();
        this.defaultImageProps = {
            cornerStyle: 'circle',
            transparentCorners: false,
            cornerColor: '#00a8ff',
            cornerSize: 8,
            padding: 5,
            strokeWidth: 0
        };
    }

    /**
     * 从URL添加图片
     */
    async addImageFromURL(url, options = {}) {
        if (!this.isEnabled() || !this.canvas) return null;

        try {
            return new Promise((resolve, reject) => {
                fabric.Image.fromURL(url, (img) => {
                    if (!img) {
                        reject(new Error('Failed to load image'));
                        return;
                    }

                    const props = {
                        ...this.defaultImageProps,
                        left: this.canvas.width / 2,
                        top: this.canvas.height / 2,
                        originX: 'center',
                        originY: 'center',
                        ...options
                    };

                    // 自动缩放图片以适应画布
                    this._scaleImageToFit(img);

                    img.set(props);
                    this.canvas.add(img);
                    this.canvas.setActiveObject(img);
                    this.canvas.renderAll();

                    this.editor._recordHistory();
                    resolve(img);
                }, {
                    crossOrigin: 'anonymous'
                });
            });
        } catch (error) {
            console.error('Failed to add image:', error);
            return null;
        }
    }

    /**
     * 从File对象添加图片
     */
    async addImageFromFile(file, options = {}) {
        if (!this.isEnabled() || !this.canvas) return null;

        try {
            const dataUrl = await this._fileToDataURL(file);
            return this.addImageFromURL(dataUrl, options);
        } catch (error) {
            console.error('Failed to add image from file:', error);
            return null;
        }
    }

    /**
     * 设置图片滤镜
     */
    applyFilter(filter) {
        if (!this.isEnabled() || !this.canvas) return;

        const activeObject = this.canvas.getActiveObject();
        if (activeObject && activeObject.type === 'image') {
            switch (filter) {
                case 'grayscale':
                    activeObject.filters.push(new fabric.Image.filters.Grayscale());
                    break;
                case 'sepia':
                    activeObject.filters.push(new fabric.Image.filters.Sepia());
                    break;
                case 'invert':
                    activeObject.filters.push(new fabric.Image.filters.Invert());
                    break;
                case 'brightness':
                    activeObject.filters.push(new fabric.Image.filters.Brightness({
                        brightness: 0.1
                    }));
                    break;
                case 'contrast':
                    activeObject.filters.push(new fabric.Image.filters.Contrast({
                        contrast: 0.1
                    }));
                    break;
                case 'saturation':
                    activeObject.filters.push(new fabric.Image.filters.Saturation({
                        saturation: 0.1
                    }));
                    break;
                case 'blur':
                    activeObject.filters.push(new fabric.Image.filters.Blur({
                        blur: 0.1
                    }));
                    break;
                case 'noise':
                    activeObject.filters.push(new fabric.Image.filters.Noise({
                        noise: 100
                    }));
                    break;
                case 'pixelate':
                    activeObject.filters.push(new fabric.Image.filters.Pixelate({
                        blocksize: 4
                    }));
                    break;
            }

            activeObject.applyFilters();
            this.canvas.renderAll();
            this.editor._recordHistory();
        }
    }

    /**
     * 清除所有滤镜
     */
    clearFilters() {
        if (!this.isEnabled() || !this.canvas) return;

        const activeObject = this.canvas.getActiveObject();
        if (activeObject && activeObject.type === 'image') {
            activeObject.filters = [];
            activeObject.applyFilters();
            this.canvas.renderAll();
            this.editor._recordHistory();
        }
    }

    /**
     * 裁剪图片
     */
    cropImage(cropRect) {
        if (!this.isEnabled() || !this.canvas) return;

        const activeObject = this.canvas.getActiveObject();
        if (activeObject && activeObject.type === 'image') {
            const { left, top, width, height } = cropRect;

            // 创建裁剪区域
            const clipPath = new fabric.Rect({
                left: left - activeObject.left,
                top: top - activeObject.top,
                width: width,
                height: height,
                absolutePositioned: true
            });

            activeObject.clipPath = clipPath;
            this.canvas.renderAll();
            this.editor._recordHistory();
        }
    }

    /**
     * 调整图片大小
     */
    resizeImage(width, height, maintainAspectRatio = true) {
        if (!this.isEnabled() || !this.canvas) return;

        const activeObject = this.canvas.getActiveObject();
        if (activeObject && activeObject.type === 'image') {
            if (maintainAspectRatio) {
                const ratio = activeObject.width / activeObject.height;
                if (width) {
                    height = width / ratio;
                } else if (height) {
                    width = height * ratio;
                }
            }

            activeObject.set({
                scaleX: width / activeObject.width,
                scaleY: height / activeObject.height
            });

            this.canvas.renderAll();
            this.editor._recordHistory();
        }
    }

    /**
     * 旋转图片
     */
    rotateImage(angle) {
        if (!this.isEnabled() || !this.canvas) return;

        const activeObject = this.canvas.getActiveObject();
        if (activeObject && activeObject.type === 'image') {
            activeObject.rotate(activeObject.angle + angle);
            this.canvas.renderAll();
            this.editor._recordHistory();
        }
    }

    /**
     * 翻转图片
     */
    flipImage(direction) {
        if (!this.isEnabled() || !this.canvas) return;

        const activeObject = this.canvas.getActiveObject();
        if (activeObject && activeObject.type === 'image') {
            if (direction === 'horizontal') {
                activeObject.set('flipX', !activeObject.flipX);
            } else if (direction === 'vertical') {
                activeObject.set('flipY', !activeObject.flipY);
            }

            this.canvas.renderAll();
            this.editor._recordHistory();
        }
    }

    /**
     * 将File对象转换为DataURL
     */
    _fileToDataURL(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (e) => resolve(e.target.result);
            reader.onerror = (e) => reject(e);
            reader.readAsDataURL(file);
        });
    }

    /**
     * 自动缩放图片以适应画布
     */
    _scaleImageToFit(img) {
        const maxWidth = this.canvas.width * 0.8;
        const maxHeight = this.canvas.height * 0.8;

        if (img.width > maxWidth || img.height > maxHeight) {
            const scale = Math.min(
                maxWidth / img.width,
                maxHeight / img.height
            );
            img.scale(scale);
        }
    }
} 